﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using Table = FCNS.Data.Table;
using System.Data;
using FSLib.IPMessager.Services;
using System.Net;
using FSLib.IPMessager.Entity;

namespace DHserver
{
    public partial class MainWindow : Window
    {
        private void StartNet()
        {
            IPAddress ip = IPAddress.Any;
            IPAddress.TryParse(DoubleHConfig.AppConfig.ServerIP, out ip);

            if (!Dns.GetHostAddresses(Dns.GetHostName()).Contains(ip))//如果不这样，当ip地址改变时运行就会报错
                ip = IPAddress.Any;

            try
            {
                lanClient = new FSLib.IPMessager.IPMClient(DoubleHConfig.AppConfig.ServerPort, "DoubleH Server", "", ip);
            }
            catch
            {
                MessageWindow.Show("host 文件异常，请清空文件再重试.");
                lanClient = null;
            }
            if (lanClient.IsInitialized)
            {
                imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));

                lanClient.OnlineHost.HostOnline += (ss, ee) => OnlineHost(ee);
                lanClient.OnlineHost.HostOffline += (ss, ee) => OfflineHost(ee);
                lanClient.Commander.MessageProcessed += new EventHandler<MessageEventArgs>(Commander_MessageProcessed);
                lanClient.FileTaskManager.TaskItemProgressChanged += new EventHandler<FSLib.IPMessager.Core.FileTaskEventArgs>(FileTaskManager_TaskItemProgressChanged);
                lanClient.FileTaskManager.TaskItemStateChanged += new EventHandler<FSLib.IPMessager.Core.FileTaskEventArgs>(FileTaskManager_TaskItemStateChanged);

                lanClient.Online();
            }
            else
                imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        }

        private void Commander_MessageProcessed(object sender, MessageEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            switch (e.Message.Command)
            {
                case FSLib.IPMessager.Define.Consts.Commands.DelMsg:
                    //这里是有原因的，如果是网络模式，例如：先添加商品的图片，但图片没有保存到服务器，
                    //这是如果又选择删除图片，图片的路径就会为客户端的本机路径，而不是网络路径。
                    //这样有可能会误删除服务器上的文件。
                    if (e.Message.NormalMsg.Contains(":\\"))
                        return;

                    int start = e.Message.NormalMsg.IndexOf("/", 7);
                    sb.Append(FCNS.Data.DbDefine.dataDir + e.Message.NormalMsg.Substring(start + 1));
                    DoubleH.Utility.Net.NetUtility.RemoveFileOnLocal(sb.Replace('/', '\\').ToString());
                    break;

                case FSLib.IPMessager.Define.Consts.Commands.SendMsg:
                    if (e.IsHandled || !e.Message.IsFileAttached) return;

                    var files = FileTaskItemHelper.DecompileTaskInfo(e.Host, e.Message);
                    if (files != null)
                    {
                        files.TaskList.ForEach(s =>
                         {
                             if (!s.IsFolder)
                                 s.FullPath = FCNS.Data.DbDefine.dataDir + e.Message.NormalMsg;
                         });
                        lanClient.FileTaskManager.AddReceiveTask(files);
                        e.IsHandled = true;
                    }

                    break;

                case FSLib.IPMessager.Define.Consts.Commands.GetDirFiles:
                    string file = FCNS.Data.DbDefine.dataDir + e.Message.NormalMsg;
                    if (!Directory.Exists(file))
                        listBoxLog.Items.Insert(0, file + " :目录不存在");
                    else
                        foreach (string str in Directory.GetFiles(file))
                            sb.Append(System.IO.Path.GetFileName(str) + ";");

                    lanClient.Commander.SendCommand(e.Host, FSLib.IPMessager.Define.Consts.Commands.GetDirFiles, 0, sb.ToString(), string.Empty);
                    break;
            }
        }

        private void FileTaskManager_ReceiveTaskFinished(object sender, FSLib.IPMessager.Core.FileTaskEventArgs e)
        {
            //System.Windows.MessageBox.Show(  e.TaskItem.CurrentName );
            //System.Windows.MessageBox.Show( e.TaskItem.FinishedSize.ToString() );
            //System.Windows.MessageBox.Show( e.TaskItem.Name  );
            //System.Windows.MessageBox.Show(   e.TaskItem.FullPath);

        }

        private void FileTaskManager_TaskItemProgressChanged(object sender, FSLib.IPMessager.Core.FileTaskEventArgs e)
        {
        }

        private void FileTaskManager_TaskItemStateChanged(object sender, FSLib.IPMessager.Core.FileTaskEventArgs e)
        {
            //System.Windows.MessageBox.Show(e.TaskItem.FullPath + " " + e.TaskItem.Name + "  " + e.TaskItem.State.ToString());
        }

        private void OnlineHost(FSLib.IPMessager.Entity.OnlineHost.HostEventArgs e)
        {
            if (e.Host == lanClient.Host)
                return;

            StationStruct obj = new StationStruct();

            obj.Host = e.Host;
            obj.LastLoginDateTime = DateTime.Now;
            obj.OperatorerName = e.Host.HostSub.UserName;
            obj.StationName = e.Host.HostSub.HostName;
            obj.StationType = e.Host.NickName;
            obj.StationIP = e.Host.HostSub.Ipv4Address.ToString();

            allStation.Add(obj);
        }

        private void OfflineHost(FSLib.IPMessager.Entity.OnlineHost.HostEventArgs e)
        {
            StationStruct obj = allStation.FirstOrDefault(f => (f.Host == e.Host));
            if (obj != null)
                allStation.Remove(obj);
        }

        private void StopNet()
        {
            if (lanClient == null)
                return;

            lanClient.OffLine();
            lanClient.Dispose();
            lanClient = null;
        }

        public void SendMessageToLan(string text, params Host[] host)
        {
            foreach (StationStruct station in allStation)
                lanClient.Commander.SendTextMessage(station.Host, text, false, false, false, false);
        }


        private void StartWeb()
        {
            if (!DoubleHConfig.AppConfig.UseBuilt_InWeb)
                return;

            DataConfig dataConfig = DoubleHConfig.AppConfig.DataConfigItems.FirstOrDefault(f => { return f.Flag == DoubleHConfig.AppConfig.DataFlag; });
            int httpPort = 80;
            if (dataConfig != null)
                httpPort = dataConfig.HttpPort;

            string processPath = FCNS.Data.DbDefine.baseDir + "WebDev.WebServer40.exe";
            string webPath = FCNS.Data.DbDefine.baseDir + "Data";
            if (!File.Exists(processPath))
            {
                MessageWindow.Show("Web服务器丢失 " + processPath + " 不存在");
                imageWeb.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
            }
            else if (!Directory.Exists(webPath))
            {
                MessageWindow.Show("Web服务器丢失 " + webPath + " 不存在");
                imageWeb.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
            }
            else
            {
                System.Windows.MessageBox.Show(processPath+ " /path:\"" + webPath + "\"  /port:" + httpPort);
                Process.Start(processPath, " /path:\"" + webPath + "\"  /port:" + httpPort);
                imageWeb.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));
            }
        }

        private void StopWeb()
        {
            if (!DoubleHConfig.AppConfig.UseBuilt_InWeb)
                return;

            foreach (Process pro in Process.GetProcessesByName("WebDev.WebServer40"))
                pro.Kill();
        }


        #region 托盘

        private void ShowNow( )
        {
            this.Visibility = System.Windows.Visibility.Visible;
            this.ShowInTaskbar = true;
            this.Activate();
        }
         
        private void CloseNow()
        {
            closeMe = true;
            this.Close();
        }
        #endregion
    }

    public class StationStruct
    {
        public FSLib.IPMessager.Entity.Host Host { get; set; }
        public string StationType { get; set; }
        public string StationName { get; set; }
        public string StationIP { get; set; }
        public string StationStatus { get; set; }
        public DateTime LastLoginDateTime { get; set; }
        public string OperatorerName { get; set; }
    }
}